package it.uai.domainsMigrator;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.SocketException;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.log4j.Logger;

public class FtpTransporter implements Runnable {

	private static final Logger logger = Logger.getLogger(FtpTransporter.class);

	private Domain dominio;
	private Integer maxItemForSingleTransfert;
	
	private ThreadManager sincronizzatore;
	
	public FtpTransporter(ThreadManager sincronizzatore, Integer maxItemForSingleTransfert){
		
		this.sincronizzatore = sincronizzatore;
		this.maxItemForSingleTransfert = maxItemForSingleTransfert;
	}

	public void connectionSetup(Domain dominio) {

		this.dominio = dominio;

	}

	public void run() {
		
		Integer contatore = 0;

		FTPClient ftp = new FTPClient();

		String currentRemotePath = dominio.getDestinationPath();

		// try to connect
		try {
			ftp.connect(dominio.getFtpServer());

			// login to server
			if (!ftp.login(dominio.getFtpUser(), dominio.getFtpPassword())) {
				ftp.logout();
				logger.debug("Nome utente e pw errati");
			}
			int reply = ftp.getReplyCode();

			// FTPReply stores a set of constants for FTP reply codes.
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftp.disconnect();
			}
			ftp.enterLocalPassiveMode();
			ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
//			logger.debug("Remote system is " + ftp.getSystemType());

			for (SingleFile file : dominio.getFiles(maxItemForSingleTransfert)) {
				
//				logger.trace("Trasferisco il file: " + file.getFile().getAbsolutePath());

				String relativePath = dominio.getDestinationPath() + file.getFile().getAbsolutePath()
						.replace(dominio.getSourcePath(), "")
						.replace(file.getFile().getName(), "");

				if (currentRemotePath != relativePath) {
					
					currentRemotePath = relativePath;
					ftp.changeWorkingDirectory(currentRemotePath);
//					logger.debug("Current directory is "
//							+ ftp.printWorkingDirectory());

				}
				
				try {
					
				InputStream input;
				input = new FileInputStream(file.getFile());

				ftp.storeFile(file.getFile().getName(), input);

				input.close();
				
				file.setTransfered();
				ftp.doCommand("chmod 755", file.getFile().getName());
				file.permitionsSetted();
				
				contatore++;
				} catch (IOException e) {
					logger.error(e);
				}

			}

			ftp.logout();
			ftp.disconnect();
			
			logger.trace("Connessione ftp chiusa, inviati " + contatore + " oggetti");
			
			sincronizzatore.exit();

		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			logger.error(e);
		}

	}
}
